import * as VueRouter from "vue-router";
import { useCookies } from "vue3-cookies";
import { useStore } from "../stores/main";

const router = VueRouter.createRouter({
  history: VueRouter.createWebHistory(),
  routes: [
    {
      path: "/",
      name: "introduce",
      component: () => import("../views/IntroducePage.vue"),
    },
    {
      path: "/faqs",
      name: "faqs",
      component: () => import("../views/FAQsPage.vue"),
    },
    {
      path: "/agreement",
      name: "agreement",
      component: () => import("../views/AgreementPage.vue"),
    },

    {
      path: "/user/sign",
      name: "user.sign",
      component: () => import("../views/User/Sign/SignPage.vue")
    },
    {
      path: "/user/profile",
      name: "user.profile",
      meta: { requiredLogin: true },
      component: () => import("../views/User/Profile/ProfilePage.vue")
    },

    {
      path: "/developer/signup",
      name: "developer.signup",
      component: () => import("../views/Developer/SignUpDeveloperPage.vue"),
      meta: { requiredLogin: true },
    },
    {
      path: "/developer",
      name: "developer.center",
      component: () => import("../views/Developer/Center/DeveloperCenterPage.vue"),
      meta: {
        requiredLogin: true,
        requirePermission: "oauth-client management",
      },
    },

    {
      path: "/oauth",
      name: "oauth.authenticate",
      meta: { requiredLogin: true },
      component: () => import("../views/OAuth/AuthenticatePage.vue"),
    },
    {
      path: "/oauth/callback",
      name: "oauth.callback",
      component: () =>
        import("../views/OAuth/AuthenticateDefaultCallbackPage.vue"),
    },

    {
      path: "/:catchAll(.*)",
      name: "errors.notfound",
      component: () => import("../views/Errors/NotFoundPage.vue"),
    }
  ],
});

router.beforeEach(async (to, from, next) => {
  if (to.meta["requiredLogin"]) {
    const { cookies } = useCookies();
    if (cookies.isKey("access_token")) {
      if (to.meta["requirePermission"]) {
        const store = useStore();
        await store.init();
        if (store.account.accountGroup != null && store.account.accountGroup.permissions.includes(to.meta["requirePermission"])) {
          next();
        } else {
          next({
            name: "introduce",
            params: {
              redirect: to.fullPath,
              i18nMesasge: true,
              message: "common.messages.require-more-permission",
            },
          });
        }
      } else {
        next();
      }
    } else {
      next({
        name: "user.sign",
        params: {
          mode: "login",
          redirect: to.fullPath,
          i18nMesasge: true,
          message: "common.messages.require-login",
        },
      });
    }
  } else {
    next();
  }
});

export default router;
